<?php

namespace backend\modules\widgets\controllers;

use Yii;
use yii\web\Controller;
use yii\helpers\FileHelper;
use yii\helpers\ArrayHelper;
use backend\models\Clients;
use backend\models\Extensions;
use backend\modules\widgets\models\Widgets;
use backend\modules\widgets\models\searchs\Widgets as WidgetsSearch;

/**
 * Default controller for the `widgets` module
 */
class DefaultController extends Controller
{
    /**
     * Renders the index view for the module
     * @return string
     */
    public function actionIndex()
    {
        $searchModel = new WidgetsSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * 编辑设置小部件
     * @param $id
     * @return string
     */
    public function actionEdit($id)
    {
        $model = Widgets::findOne($id);
        $extension = Extensions::findOne(['element' => $model->widget, 'type' => 'widget']);

        if (Yii::$app->request->isPost) {
            if ($model->load(Yii::$app->request->post()) && $model->save()) {
                return $this->redirect(['index']);
            }
        }

        return $this->render('edit', [
            'model' => $model,
            'extension' => $extension,
            'positions' => $this->getPosition($model->client_id),
            'configs' => $this->getConfigs($model->client_id, $model->widget)
        ]);
    }

    protected function getPosition($clientId)
    {
        $client = Clients::findOne($clientId);
        $themesPath = Yii::getAlias('@root') . $client->path . '/themes';
        $themesPaths = FileHelper::findDirectories($themesPath, ['recursive' => false]);
        $positions = [];
        foreach ($themesPaths as $path) {
            $xmlFile = $path . '/themeDetails.xml';
            if (is_file($xmlFile)) {
                $extension = Extensions::findOne(['type' => 'theme', 'element' => basename($path)]);
                $langCat = $extension->manifest_cache['langCat'] ?? null;
                if ($langCat) {
                    Yii::$app->i18n->translations[$langCat] = [
                        'class' => 'yii\i18n\PhpMessageSource',
                        'basePath' => '@' . $client->name . '/themes/' . basename($path) . '/messages'
                    ];
                }
                $xml = simplexml_load_file($xmlFile);
                $xmlPosition = (array)$xml->positions->position;
                $valPosition = array_map(function ($pos) use ($langCat) {
                    return ($langCat ? Yii::t($langCat, strtoupper('position_' . $pos)) : '') . ' [' . $pos . ']';
                }, $xmlPosition);
                $positions[ucfirst((string)$xml->element)] = array_combine($xmlPosition, $valPosition);
            }
        }
        $customPositions = Widgets::find()
            ->select('DISTINCT(position)')
            ->where(['client_id' => $clientId])
            ->orderBy('position')
            ->asArray()
            ->all();
        $customPosition = ArrayHelper::getColumn($customPositions, 'position');
        $positions[Yii::t('mod_widgets', 'CUSTOM_POSITION')] = array_combine($customPosition, $customPosition);
        return $positions;
    }

    protected function getConfigs($clientId, $widget)
    {
        $client = Clients::findOne($clientId);
        $xmlFile = Yii::getAlias('@root/') . $client->name . '/widgets/' . $widget . '/widget.xml';
        if (is_file($xmlFile)) {
            $xml = simplexml_load_file($xmlFile);
            return $xml->config;
        } else {
            return [];
        }
    }
}
